<template>
	<el-cascader
		size="small"
		:options="options"
		v-model="selectedOptions"
		v-bind="$attrs"
	></el-cascader>
</template>

<script>
	import {
		provinceAndCityData,
		regionData,
		// provinceAndCityDataPlus,
		// regionDataPlus,
		CodeToText,
		TextToCode
	} from "element-china-area-data";
	export default {
		name: "area-selector",
		components: {},
		props: {
			type: {
				type: String,
				default: "regionData"
			},
			value: {
				type: Array,
				default: () => []
			},
			valueFormat: {
				type: String,
				default: "code" //code  text  all
			}
		},
		data() {
			return {
				selectedOptions: this.value
			};
		},
		watch: {
			value(val) {
				this.selectedOptions = val;
			},
			selectedOptions: {
				handler(val) {
					this.handleChange(val);
				},
				immediate: true
			}
		},
		computed: {
			options() {
			  this.selectedOptions = this.value;
				switch (this.type) {
					case "provinceData":
						return provinceAndCityData.map(i => ({
							label: i.label,
							value: i.value
						}));
						break;
					case "provinceAndCityData":
						return provinceAndCityData;
						break;
					default:
						return regionData;
						break;
				}
			}
		},
		methods: {
			handleChange(value) {
				let text = [];
				if (value.length > 0) {
					text = this.code2Text(value);
				}
				this.$emit("input", value);
				this.$emit("change", text);
			},
			code2Text(val) {
				if (Array.isArray(val) && val.length > 0) {
					return val.map(i => {
						return this.code2Text(i);
					});
				} else {
					return CodeToText[val];
				}
			}
		}
	};
</script>
